package com.jumi.microservice.rocketmq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jumi.microservice.common.utils.DateUtil;
import com.jumi.microservice.domain.MessageTemplate;
import com.jumi.microservice.entity.OrderGoods;
import com.jumi.microservice.entity.UserOrder;
import com.jumi.microservice.enumerate.OrderStatusEnum;
import com.jumi.microservice.mapper.OrderGoodsMapper;
import com.jumi.microservice.mapper.UserOrderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author mazhao
 * @Date 2020-09-17 11:50
 */
@Component
public class UnPayOrderListener implements MessageListener {

    private static final Logger log = LoggerFactory.getLogger(UnPayOrderListener.class);

    @Resource
    SendMessageHandler sendMessageHandler;
    @Resource
    UserOrderMapper userOrderMapper;
    @Resource
    OrderGoodsMapper orderGoodsMapper;
    @Resource
    ProducerBean producerBean;
    @Resource
    private RedisTemplate<String,String> redisTemplate;

    private static final String key = "isUnPayOrder::";

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        log.info("从unPay队列收到消息 [{}]", new String(message.getBody()));
        JSONObject jsonObject;
        try {
            jsonObject = JSON.parseObject(new String(message.getBody()));
        } catch (Exception e) {
            log.error("JSON解析消息出错 [{}]",e.getMessage());
            return  Action.CommitMessage;
        }
        String orderNo = jsonObject.getString("orderSn");
        Boolean res = redisTemplate.opsForValue().setIfAbsent(key+orderNo,"待支付订单",7, TimeUnit.DAYS);
        if(res!=null && !res){
            log.info("待支付订单重复：[{}]", orderNo);
            return Action.CommitMessage;
        }
        QueryWrapper<UserOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo).eq("order_status", OrderStatusEnum.READY_TO_PAY.getCode())
                .eq("del_flag", 0);
        UserOrder userOrder = userOrderMapper.selectOne(queryWrapper);
        if (userOrder == null) {
            log.info("该订单已支付或处于其他状态");
            return Action.CommitMessage;
        }
        QueryWrapper<OrderGoods> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("order_no", orderNo).eq("del_flag", 0);
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(queryWrapper1);
        if (orderGoodsList.isEmpty()) {
            log.info("该订单下不存在商品");
            return Action.CommitMessage;
        }
        BigDecimal orderPromotionAmount = BigDecimal.ZERO;
        BigDecimal payAmount = BigDecimal.ZERO;
        for (OrderGoods orderGoods : orderGoodsList) {
            orderPromotionAmount = orderPromotionAmount.add(orderGoods.getGoodsPromotionPrice().multiply(new BigDecimal(orderGoods.getGoodsAmount())));
            payAmount = payAmount.add(orderGoods.getGoodsPrice().multiply(new BigDecimal(orderGoods.getGoodsAmount())));
        }
        MessageTemplate messageTemplate = sendMessageHandler.getMessageTemplate(2);
        String appMessageContent = messageTemplate==null?"":messageTemplate.getSmtAppContent()
                .replace("{}", payAmount.toString());
        String stationMessageContent = messageTemplate==null?"":messageTemplate.getSmtMessageContent()
                .replace("{}", payAmount.toString());
        //待支付提醒
        log.info("支付前5分钟未支付推送通知");
        sendMessageHandler.sendMessage(userOrder.getOrderNo(), appMessageContent, stationMessageContent,
                "", "", "", orderGoodsList.get(0).getGoodsCoverImg(),
                userOrder.getBuyerId(), 2, orderPromotionAmount, payAmount, orderGoodsList.get(0).getGoodsName(),
                orderGoodsList.get(0).getFreeGoods());
        //转发订单支付时间超时队列
        try {
            log.info("转发超时未支付队列");
            Message sendMessage = new Message("unPayTimeOut", "", "", JSON.toJSONBytes(userOrder));
            sendMessage.setStartDeliverTime(userOrder.getFailureTime().getTime());
            producerBean.send(sendMessage);
        } catch (Exception e) {
            log.error("转发超时未支付队列出错 [{}]",e.getMessage());
            redisTemplate.delete(key+orderNo);
            return Action.ReconsumeLater;
        }
        return Action.CommitMessage;
    }
}
